<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人中心 - 类似淘宝</title>
    <!-- 引入Bootstrap CSS -->
    <link rel="stylesheet" href="/assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="/dist/js/bootstrap.bundle.js">
    <!-- 引入Font Awesome图标 -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f5f5f5;
        }
        .navbar {
            background-color: #804D4E; /* 顶部大边框背景色 */
        }
        .navbar-brand {
            color: #fff !important;
            font-weight: bold;
        }
        .navbar-brand:hover {
            color: #f8f9fa !important; /* 悬停时的颜色 */
        }
        .sidebar {
            background-color: #fff;
            height: 100vh;
            box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
        }
        .sidebar .nav-link {
            color: #333;
            font-weight: 500;
            padding: 10px 15px;
            border-radius: 5px;
            margin-bottom: 5px;
            transition: all 0.3s ease;
        }
        .sidebar .nav-link:hover {
            background-color: #804D4E; /* 鼠标悬停背景色 */
            color: #fff !important;
        }
        .sidebar .nav-link.active {
            background-color: #804D4E; /* 选中状态背景色 */
            color: #fff !important;
        }
        .main-content {
            padding: 20px;
            background-color: #f5f5f5;
        }
        .card {
            margin-bottom: 20px;
            border: none;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
        .card-header {
            background-color: #fff;
            border-bottom: 1px solid #eee;
        }
        .btn-primary {
            background-color: #804D4E;
            border-color: #804D4E;
        }
        .btn-primary:hover {
            background-color: #6a3d3e;
            border-color: #6a3d3e;
        }
        .user-avatar {
            width: 100px; /* 容器宽度 */
            height: 100px; /* 容器高度 */
            border-radius: 50%; /* 圆形 */
            overflow: hidden; /* 隐藏超出部分 */
            border: 3px solid #804D4E; /* 圆框边框 */
            cursor: pointer; /* 鼠标指针样式 */
            transition: transform 0.3s ease; /* 悬停动画 */
            display: flex; /* 使用 Flexbox 居中图片 */
            justify-content: center; /* 水平居中 */
            align-items: center; /* 垂直居中 */
        }
        .user-avatar:hover {
            transform: scale(1.1); /* 悬停放大效果 */
        }
        .user-avatar img {
            width: 100%; /* 图片宽度填满容器 */
            height: 100%; /* 图片高度填满容器 */
            object-fit: cover; /* 保持图片比例，裁剪超出部分 */
        }
        .hidden {
            display: none; /* 隐藏元素 */
        }
        .address-input {
            display: flex;
            gap: 10px;
        }
        .address-input input {
            flex: 1;
            cursor: pointer;
        }
    </style>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>




<!-- 顶部导航栏 -->
<nav class="navbar navbar-expand-lg navbar-dark">
    <div class="container-fluid">
        <!-- 返回首页的超链接 -->
        <a class="navbar-brand me-3" href="index.html" style="color: #fff; text-decoration: none;">
            <i class="fas fa-home"></i> 返回首页
        </a>
        <a class="navbar-brand" href="#">个人中心</a>

        <ul class="navbar-nav ms-3">
            <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                    <i class="fas fa-user-circle"></i> 我的账号
                </a>
                <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
                    <li><hr class="dropdown-divider"></li>
                    <li><a class="dropdown-item" href="#" id="logout-btn">退出登录</a></li>
                </ul>
            </li>
        </ul>
    </div>
</nav>

<!-- 侧边栏和主内容区 -->
<div class="container-fluid">
    <div class="row">
        <!-- 侧边栏 -->
        <div class="col-md-2 sidebar">
            <div class="d-flex flex-column p-3">
                <div class="text-center mb-4">
                    <!-- 用户头像 -->
                    <div class="user-avatar" onclick="document.getElementById('avatar-input').click()">
                        <img id="avatar-img" src="" alt="用户头像">
                    </div>
                    <input type="file" id="avatar-input" accept="image/*" style="display: none;" onchange="uploadAvatar(event)">
                    <h5 id="username" class="mt-2">加载中...</h5>
                </div>
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a class="nav-link" href="#" onclick="showSection('home')">
                            <i class="fas fa-home me-2"></i> 首页
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#" onclick="showSection('orders')">
                            <i class="fas fa-list-alt me-2"></i> 我的订单
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#" onclick="showSection('profile')">
                            <i class="fas fa-user me-2"></i> 我的个人信息
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">
                            <i class="fas fa-cog me-2"></i> 设置
                        </a>
                    </li>
                </ul>
            </div>
        </div>

        <!-- 主内容区 -->
        <div class="col-md-10 main-content">
            <!-- 首页内容 -->
            <div id="home-section" class="section">
                <h3>欢迎来到个人中心</h3>
                <p>请从侧边栏选择功能。</p>
            </div>

            <!-- 我的订单内容 -->
            <div id="orders-section" class="section hidden">
                <h3>我的订单</h3>
                <div class="card">
                    <div class="card-header">
                        订单列表
                    </div>
                    <div class="card-body">
                        <table class="table table-striped">
                            <thead>
                            <tr>
                                <th>订单号</th>
                                <th>总价</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody id="orders-table-body">
                            <!-- 动态填充数据 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- 我的个人信息内容 -->
            <div id="profile-section" class="section hidden">
                <h3>我的个人信息</h3>
                <div class="card">
                    <div class="card-header">
                        个人信息
                    </div>
                    <div class="card-body">
                        <form id="profile-form">
                            <div class="mb-3">
                                <label for="profile-username" class="form-label">用户名</label>
                                <input type="text" class="form-control" id="profile-username" value="张三">
                            </div>
                            <div class="mb-3">
                                <label for="profile-phone" class="form-label">手机号</label>
                                <input type="tel" class="form-control" id="profile-phone" value="12345678901">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">地址</label>
                                <div class="address-input">
                                    <input type="text" id="province" class="form-control" placeholder="省" readonly onclick="showAreaPicker('province')">
                                    <input type="text" id="city" class="form-control" placeholder="市" readonly onclick="showAreaPicker('city')">
                                    <input type="text" id="district" class="form-control" placeholder="区" readonly onclick="showAreaPicker('district')">
                                </div>
                            </div>
                            <button type="button" class="btn btn-primary" onclick="saveProfile()">保存</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 省市区选择模态框 -->
<div id="area-picker-modal" class="modal fade" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">选择地址</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label for="province-select" class="form-label">省</label>
                    <select id="province-select" class="form-control" onchange="loadCities()"></select>
                </div>
                <div class="mb-3">
                    <label for="city-select" class="form-label">市</label>
                    <select id="city-select" class="form-control" onchange="loadDistricts()"></select>
                </div>
                <div class="mb-3">
                    <label for="district-select" class="form-label">区</label>
                    <select id="district-select" class="form-control"></select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="confirmAddress()">确认</button>
            </div>
        </div>
    </div>
</div>











<script>
    // 显示订单模块时加载数据
    function showOrders() {
        // 1. 显示订单模块
        document.querySelectorAll('.section').forEach(section => {
            section.classList.add('hidden');
        });
        document.getElementById('orders-section').classList.remove('hidden');

        // 2. 获取当前用户的 ID（假设从全局变量或登录信息中获取）
        //访问/api/user-info获取userid

        fetch('/api/user-info')
            .then(response => response.json())
            .then(data => {
                const userid = data.id; // 假设后端返回的 JSON 结构为 { userid: 123 }
                fetch(`/api/orders/my-orders?userid=${userid}`)
                    .then(response => response.json())
                    .then(data => {
                        const  orders = data.orders; // 订单列表
                        const orderDetails = data.orderDetails; // 订单商品详情列

                        // 4. 填充数据到表格
                        const tbody = document.getElementById('orders-table-body');
                        tbody.innerHTML = ''; // 清空现有数据

                        orders.forEach(order => {
                            // 找到当前订单对应的商品详情
                            const details = orderDetails.filter(detail => detail.orderid === order.id);
                            console.log(details);
                            console.log(order);
                            const row = `
                        <tr>
                            <td>${order.code}</td>
                            <td>¥${order.money.toFixed(2)}</td>
                            <td>${order.state}</td>
                            <td>
                                <button class="btn btn-sm btn-primary" onclick="viewOrderDetail(${order.id})">查看详情</button>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="4">
                                <table class="table table-bordered">
                                    <thead>
                                        <tr>
                                            <th>商品名称</th>
                                            <th>图片</th>
                                            <th>单价</th>
                                            <th>数量</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        ${details.map(detail => `
                                            <tr>
                                                <td>${detail.productname}</td>
                                                <td><img src="${detail.imgurl}" width="50" height="50"></td>
                                                <td>¥${detail.price.toFixed(2)}</td>
                                                <td>${detail.number}</td>
                                            </tr>
                                        `).join('')}
                                    </tbody>
                                </table>
                            </td>
                        </tr>
                    `;
                            tbody.insertAdjacentHTML('beforeend', row);
                        });
                    })
                    .catch(error => {
                        console.error('Error fetching orders:', error);
                    });

            })


        // 替换为实际的用户 ID

        // 3. 调用后端 API 获取订单数据

    }

    // 查看订单详情
    function viewOrderDetail(orderId) {
        alert(`查看订单详情：${orderId}`);
        // 这里可以跳转到订单详情页面或弹出模态框
    }

    // 绑定点击事件
    document.querySelector('a[onclick="showSection(\'orders\')"]').addEventListener('click', showOrders);
</script>






<!-- 引入Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<!-- 引入高德地图 API 和 DistrictSearch 插件 -->
<script src="https://webapi.amap.com/maps?v=2.0&key=afaf7ba5bc867dec5e8bb765ef9296db&plugin=AMap.DistrictSearch"></script>
<script>
    // 优化后的 JavaScript 代码
    let currentAreaType = ''; // 当前选择的地址类型（province/city/district）
    let cachedProvinces = null; // 缓存省份数据

    // 显示对应的内容区域
    function showSection(sectionId) {
        document.querySelectorAll('.section').forEach(section => {
            section.classList.add('hidden');
        });
        document.getElementById(`${sectionId}-section`).classList.remove('hidden');
    }

    // 上传头像
    function uploadAvatar(event) {
        const file = event.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function (e) {
                document.getElementById('avatar-img').src = e.target.result;
                const formData = new FormData();
                formData.append('avatar', file);
                fetch('/upload-avatar', {
                    method: 'POST',
                    body: formData
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            alert('头像已更新！文件名：' + data.filename);
                        } else {
                            alert('头像更新失败：' + data.message);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('头像更新失败，请重试！');
                    });
            };
            reader.readAsDataURL(file);
        }
    }

    // 获取用户信息
    async function fetchUserInfo() {
        try {
            const response = await fetch('/api/user-info', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) {
                throw new Error('网络响应失败');
            }

            const data = await response.json();
            console.log(data);

            // 更新用户信息
            document.getElementById('avatar-img').src = "\\assets\\picture\\"+data.imgurl;
            document.getElementById('username').textContent = data.username;
            document.getElementById('profile-phone').value = data.tel;
            document.getElementById('profile-username').value = data.username;
            document.getElementById('province').value = data.address?.province || '';
            document.getElementById('city').value = data.address?.city || '';
            document.getElementById('district').value = data.address?.district || '';
        } catch (error) {
            console.error('获取用户信息失败:', error);
            alert('无法加载用户信息，请稍后重试！');
        }
    }

    // 保存个人信息
    async function saveProfile() {
        const username = document.getElementById('profile-username').value;
        const phone = document.getElementById('profile-phone').value;
        const province = document.getElementById('province').value;
        const city = document.getElementById('city').value;
        const district = document.getElementById('district').value;

        const profileData = {
            username: username,
            tel: phone,
            useraddress: {
                province: province,
                city: city,
                area: district,
            }
        };

        try {
            const response = await fetch('/api/update-profile', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(profileData)
            });

            if (!response.ok) {
                throw new Error('保存失败');
            }

            const data = await response.json();
            alert('保存成功！');
        } catch (error) {
            console.error('保存失败:', error);
            alert('保存失败，请重试！');
        }
    }

    // 显示省市区选择器
    function showAreaPicker(type) {
        currentAreaType = type;
        $('#area-picker-modal').modal('show');
        if (type === 'province') {
            setTimeout(loadProvinces, 0); // 异步加载
        }
    }

    // 加载省份
    function loadProvinces() {
        if (cachedProvinces) {
            updateProvinceSelect(cachedProvinces);
            return;
        }

        // 创建 JSONP 回调函数
        window.jsonpCallback = function (response) {
            if (response.status === '1') {
                cachedProvinces = response.districts[0].districts;
                updateProvinceSelect(cachedProvinces);
            } else {
                console.error('加载省份失败:', response.info);
                alert('加载省份数据失败，请检查网络或 API Key！');
            }
        };

        // 动态创建 script 标签，发起 JSONP 请求
        const script = document.createElement('script');
        script.src = `https://restapi.amap.com/v3/config/district?key=afaf7ba5bc867dec5e8bb765ef9296db&keywords=中国&subdistrict=1&output=json&callback=jsonpCallback`;
        document.body.appendChild(script);
    }

    // 更新省份选择器
    function updateProvinceSelect(provinces) {
        const provinceSelect = document.getElementById('province-select');
        provinceSelect.innerHTML = provinces.map(province => `
            <option value="${province.name}">${province.name}</option>
        `).join('');
        loadCities();
    }

    // 加载城市
    function loadCities() {
        const province = document.getElementById('province-select').value;

        // 创建 JSONP 回调函数
        window.jsonpCallback = function (response) {
            if (response.status === '1') {
                const cities = response.districts[0].districts;
                const citySelect = document.getElementById('city-select');
                citySelect.innerHTML = cities.map(city => `
                    <option value="${city.name}">${city.name}</option>
                `).join('');
                loadDistricts();
            } else {
                console.error('加载城市失败:', response.info);
                alert('加载城市数据失败，请检查网络或 API Key！');
            }
        };

        // 动态创建 script 标签，发起 JSONP 请求
        const script = document.createElement('script');
        script.src = `https://restapi.amap.com/v3/config/district?key=afaf7ba5bc867dec5e8bb765ef9296db&keywords=${encodeURIComponent(province)}&subdistrict=1&output=json&callback=jsonpCallback`;
        document.body.appendChild(script);
    }

    // 加载区县
    function loadDistricts() {
        const city = document.getElementById('city-select').value;

        // 创建 JSONP 回调函数
        window.jsonpCallback = function (response) {
            if (response.status === '1') {
                const districts = response.districts[0].districts;
                const districtSelect = document.getElementById('district-select');
                districtSelect.innerHTML = districts.map(district => `
                    <option value="${district.name}">${district.name}</option>
                `).join('');
            } else {
                console.error('加载区县失败:', response.info);
                alert('加载区县数据失败，请检查网络或 API Key！');
            }
        };

        // 动态创建 script 标签，发起 JSONP 请求
        const script = document.createElement('script');
        script.src = `https://restapi.amap.com/v3/config/district?key=afaf7ba5bc867dec5e8bb765ef9296db&keywords=${encodeURIComponent(city)}&subdistrict=1&output=json&callback=jsonpCallback`;
        document.body.appendChild(script);
    }

    // 确认选择的地址
    function confirmAddress() {
        const province = document.getElementById('province-select').value;
        const city = document.getElementById('city-select').value;
        const district = document.getElementById('district-select').value;

        // 更新所有地址栏的值
        document.getElementById('province').value = province;
        document.getElementById('city').value = city;
        document.getElementById('district').value = district;

        // 隐藏模态框
        $('#area-picker-modal').modal('hide');
    }

    // 页面加载完成后调用
    window.onload = function () {
        showSection('home'); // 默认显示首页
        fetchUserInfo(); // 获取用户信息
    };
</script>

<script>
    document.addEventListener("DOMContentLoaded", function () {
        // 获取退出登录按钮
        const logoutBtn = document.getElementById("logout-btn");

        // 绑定点击事件
        logoutBtn.addEventListener("click", function (event) {
            event.preventDefault(); // 阻止默认跳转行为

            // 发送退出登录请求
            fetch("/api/logout", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                credentials: "include" // 确保携带 cookie（如果使用 session）
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 0) {
                        // 退出登录成功，跳转到首页
                        window.location.href = "/index.html";
                    } else {
                        alert("退出登录失败：" + data.message);
                    }
                })
                .catch(error => {
                    console.error("Error:", error);
                    alert("退出登录失败，请重试！");
                });
        });
    });






</script>
</body>
</html>